using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Tilver.DBConnectionUI.Editors
{
    internal static class OdbcManager
    {
        [DllImport("odbc32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern short SQLAllocEnv(ref int env);
        
        [DllImport("odbc32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern short SQLAllocConnect(int env, ref int lHdbc);
        
        [DllImport("ODBC32.DLL", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern short SQLDriverConnect(int hDBC, int hWnd, string constr, short constrlen, StringBuilder buf, short buflen, ref short outlen, short prompt);
        
        [DllImport("odbc32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern short SQLFreeConnect(int lHdbc);
        
        [DllImport("odbc32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern short SQLFreeEnv(int env);
        
        [DllImport("odbc32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern short SQLDisconnect(int lHdbc);

        /// <summary>
        /// displays the odbc management console and returns the built connection string
        /// </summary>
        public static string GetODBCConnectionString(Form ownerForm)
        {

            //const short SQL_NTS = -3; //Null-terminated string
            //const short SQL_NOSCAN = 2;
            //const short SQL_NOSCAN_ON = 1;
            //const short SQL_NULL_HENV = 0;
            //const short SQL_NULL_HDBC = 0;
            //const short SQL_NULL_HSTMT = 0;
            const short SQL_SUCCESS = 0;
            //const short SQL_DROP = 1;
            //const short MAXBUFLEN = 255;
            const short SQL_DRIVER_PROMPT = 2;

            StringBuilder Buf =  new StringBuilder(0x400);
            string constr = "";
            short outlen = 0;
            short Retcode = 0;
            int hEnv = 0;
            int hDBC = 0;

            if (SQLAllocEnv(ref hEnv) == SQL_SUCCESS)
            {
                if (SQLAllocConnect(hEnv, ref hDBC) == SQL_SUCCESS)
                {
                    if (SQLDriverConnect(hDBC, ownerForm.Handle.ToInt32(), constr, (short)constr.Length, Buf, 0x400, ref outlen, SQL_DRIVER_PROMPT) == SQL_SUCCESS)
                    {
                        //MessageBox.Show(Buf.ToString());
                        Retcode = SQLDisconnect(hDBC);
                    }
                    Retcode = SQLFreeConnect(hDBC);
                }
                Retcode = SQLFreeEnv(hEnv);
            }

            return Buf.ToString();
        }
    }

}
